//
// Created by klen on 23-12-5.
//
#include "page.h"
#include "file.h"

shared_ptr<ComponentBase> ModelComponent(shared_ptr<string> msg, shared_ptr<bool> showModel) {
    auto btn = Button("确定", [=] {
        *showModel = false;
    });

    return Renderer(btn, [=] {
        return vbox({
            text(*msg),
            btn->Render()
        }) | border;
    });
}

shared_ptr<ComponentBase> getPage() {

    shared_ptr<string> startDir{make_shared<string>()};
    shared_ptr<string> targetName{make_shared<string>()};
    shared_ptr<vector<string>> filenames{make_shared<vector<string>>()};
    shared_ptr<string> errString {make_shared<string>()};
    shared_ptr<bool> showErr{make_shared<bool>()};

    auto input_startDir = Input(startDir.get());
    auto input_targetName = Input(targetName.get());
    auto selected = make_shared<int>();
    auto fileFrame = Menu(filenames.get(), selected.get());



    auto search = [=] {
        if (targetName->empty()) {
            *errString = "搜索文件名不可为空";
            *showErr = true;
            return ;
        }

        auto [searchFiles, err] = SearchFile(path{*startDir}, *targetName);
        if (!err.empty()) {
            *errString = err;
            *showErr = true;
            return;
        }

        filenames->clear();
        for (const auto& file : searchFiles) {
            filenames->push_back(file.path());
        }
    };

    auto button_search = Button("搜索", search);

    auto component = Renderer(Container::Horizontal({input_startDir,
                                           input_targetName,
                                           button_search,
                                           fileFrame
                                           }),
    [=]{

        return vbox({
                            text("文件查找器") | center,
                            hbox({
                                         vbox({
                                                      hbox({
                                                          text("请输入搜索目录"),
                                                          input_startDir->Render(),
                                                      }) | size(WIDTH, GREATER_THAN, 100),
                                                      hbox({
                                                          text("请输入搜索文件"),
                                                          input_targetName->Render(),
                                                      }) | size(WIDTH, GREATER_THAN, 100),
                                         }) ,
                                         button_search->Render() | size(HEIGHT, EQUAL, 3) ,

                            }) | xflex,
                            fileFrame->Render() | vscroll_indicator | frame | size(HEIGHT, GREATER_THAN, 10) |size(HEIGHT, LESS_THAN, 20) | border

        });
    });

    component |= Modal(ModelComponent(errString, showErr), showErr.get());
    return component;
}

